import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:live_music/components/common/RoundUnderlineTabIndicator.dart';
import 'package:live_music/components/ui/tag.dart';
import 'package:live_music/components/ui/theme.dart';
import 'package:live_music/controller/userInfo_controller.dart';
import 'package:live_music/models/user_info_model.dart';
import 'package:live_music/pages/friendList/index.dart';
import 'package:live_music/pages/home/mime/widget/collect_mime.dart';
import 'package:live_music/pages/home/mime/widget/liked_mime.dart';
import 'package:live_music/pages/home/mime/widget/note_mine.dart';
import 'package:live_music/pages/home/mime/widget/topic_mime.dart';
import 'package:live_music/pages/setting/index.dart';
import 'package:live_music/pages/userInfo/index.dart';
import 'package:live_music/utils/cgq_utils.dart';
import 'package:live_music/utils/colors.dart';
import 'package:live_music/utils/util.dart';

class PageViewMime extends StatefulWidget {
  const PageViewMime({Key key}) : super(key: key);

  @override
  State<PageViewMime> createState() => _PageViewMimeState();
}

class _PageViewMimeState extends State<PageViewMime>
    with AutomaticKeepAliveClientMixin, SingleTickerProviderStateMixin {
  TabController _tabController;
  UserInfoController _userInfoController = Get.put(UserInfoController());
  List<Widget> _tabsContent;
  List<Widget> _tabs;
  UserInfoModel userInfo = UserInfoModel();
  DateTime lastRefreshTime = DateTime.now();
  NoteMimeWidget _noteMimeWidget = NoteMimeWidget();
  TopicMimeWidget _topicMimeWidget = TopicMimeWidget();
  CollectMimeWidget _collectMimeWidget = CollectMimeWidget();
  LikeMimeWidget _likeMimeWidget = LikeMimeWidget();
  double _appBarOpacity = 0;
  @override
  void initState() {
    super.initState();
    _tabsContent = [
      _noteMimeWidget,
      _topicMimeWidget,
      _collectMimeWidget,
      _likeMimeWidget
    ];
    _tabs = [
      Text('笔记'),
      Text('话题'),
      Text('收藏'),
      Text('赞过'),
    ];
    _tabController = TabController(
      initialIndex: 0,
      length: _tabs.length,
      vsync: this,
    );
    loadData();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  loadData() {
    _userInfoController.getUserInfo();
    _userInfoController.loadCountInfo();
    _userInfoController.loadUserSetting();
  }

  Future onRefresh() async {
    if (_tabController.index == 0) {
      await _noteMimeWidget.onRefresh();
    } else if (_tabController.index == 1) {
      await _topicMimeWidget.onRefresh();
    } else if (_tabController.index == 2) {
      await _collectMimeWidget.onRefresh();
    } else if (_tabController.index == 3) {
      await _likeMimeWidget.onRefresh();
    }
    loadData();
  }

  double maxOffset = 340.0;
  scrollViewDidScrolled(double offSet) {
    double appBarOpacity = offSet / maxOffset;
    if (appBarOpacity < 0) {
      appBarOpacity = 0.0;
    } else if (appBarOpacity > 1) {
      appBarOpacity = 1.0;
    }
    setState(() {
      _appBarOpacity = appBarOpacity;
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return RefreshIndicator(
        color: ColorRes.tabLine,
        onRefresh: onRefresh,
        notificationPredicate: (notification) {
          if (notification is ScrollUpdateNotification &&
              notification.depth == 0) {
            scrollViewDidScrolled(notification.metrics.pixels);
          }
          return true;
        },
        child: ExtendedNestedScrollView(
            onlyOneScrollInBody: true,
            headerSliverBuilder: ((context, innerBoxIsScrolled) {
              return [
                Obx(() {
                  return SliverAppBar(
                    backgroundColor: Colors.white,
                    automaticallyImplyLeading: false,
                    pinned: true,
                    expandedHeight: 420,
                    actions: [
                      IconButton(
                        icon: Icon(
                          Icons.settings_outlined,
                          size: WcaoTheme.fsBase * 1.6,
                          color: WcaoTheme.base,
                        ),
                        onPressed: () async {
                          Get.to(SettingsPage());
                        },
                      )
                    ],
                    centerTitle: true,
                    title: LayoutBuilder(builder: (context, constraints) {
                      return AnimatedOpacity(
                          duration: const Duration(microseconds: 300),
                          opacity: _appBarOpacity,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              SizedBox(
                                  width: 30,
                                  child: CircleAvatar(
                                    radius: 15,
                                    backgroundImage: NetworkImage(
                                      _userInfoController
                                          .userInfo.value.avatarUrl,
                                    ),
                                  )),
                              SizedBox(
                                width: 6,
                              ),
                              Text(
                                _userInfoController.userInfo.value.name,
                                style: TextStyle(
                                  color: WcaoTheme.base,
                                  fontSize: 14,
                                ),
                              ),
                            ],
                          ));
                    }),
                    flexibleSpace: LayoutBuilder(
                      builder: (context, constraints) {
                        return FlexibleSpaceBar(
                          background: Stack(
                            children: [
                              SizedBox(
                                width: double.infinity,
                                child: CgqUtils.imageCache(
                                  _userInfoController.userInfo.value.bgUrl,
                                  fit: BoxFit.cover,
                                ),
                              ),
                              Positioned(
                                child: Container(
                                  color: Colors.black.withOpacity(.33),
                                ),
                              ),
                              Positioned(
                                bottom: 96,
                                width: MediaQuery.of(context).size.width,
                                child: profile(_userInfoController),
                              )
                            ],
                          ),
                        );
                      },
                    ),
                    bottom: TabBarWidget(tabController: _tabController, tabs: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          _userInfoController.userSetting.value.isShowMoment ==
                                  0
                              ? Icon(
                                  Icons.lock,
                                  size: WcaoTheme.fsBase * 1.2,
                                  color: Colors.grey,
                                )
                              : Container(),
                          Text('笔记')
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          _userInfoController.userSetting.value.isShowTopic == 0
                              ? Icon(
                                  Icons.lock,
                                  size: WcaoTheme.fsBase * 1.2,
                                  color: Colors.grey,
                                )
                              : Container(),
                          Text('话题')
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          _userInfoController
                                      .userSetting.value.isShowCollected ==
                                  0
                              ? Icon(
                                  Icons.lock,
                                  size: WcaoTheme.fsBase * 1.2,
                                  color: Colors.grey,
                                )
                              : Container(),
                          Text('收藏')
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          _userInfoController.userSetting.value.isShowLiked == 0
                              ? Icon(
                                  Icons.lock,
                                  size: WcaoTheme.fsBase * 1.2,
                                  color: Colors.grey,
                                )
                              : Container(),
                          Text('赞过')
                        ],
                      )
                    ]),
                  );
                }),
              ];
            }),
            body: Container(
                child: TabBarView(
              controller: _tabController,
              children: _tabsContent,
            ))));
  }

  @override
  bool get wantKeepAlive => true;
}

class TabBarWidget extends StatefulWidget implements PreferredSizeWidget {
  final TabController tabController;
  final List<Widget> tabs;
  TabBarWidget({Key key, this.tabController, this.tabs}) : super(key: key);
  @override
  _TabBarWidgetState createState() => _TabBarWidgetState();
  @override
  Size get preferredSize => Size.fromHeight(44);
}

class _TabBarWidgetState extends State<TabBarWidget> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;
    return Container(
        width: screenWidth,
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(15), topRight: Radius.circular(15))),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
                width: 0.75 * screenWidth,
                padding: EdgeInsets.only(top: 15, bottom: 10),
                alignment: Alignment.center,
                child: TabBar(
                  indicatorSize: TabBarIndicatorSize.label,
                  controller: widget.tabController,
                  indicatorColor: ColorRes.tabLine,
                  indicatorWeight: 2,
                  indicator: RoundUnderlineTabIndicator(
                      borderSide: BorderSide(
                    width: 2,
                    color: ColorRes.tabLine,
                  )),
                  unselectedLabelStyle: TextStyle(
                      color: Colors.black, // 下划线颜色
                      fontSize: 14,
                      fontWeight: FontWeight.w600),
                  labelStyle: TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                      fontWeight: FontWeight.w700), //标签文字大小颜色
                  tabs: widget.tabs,
                )),
          ],
        ));
  }
}

Column adapterItem(int num, String text) {
  return Column(
    crossAxisAlignment: CrossAxisAlignment.center,
    children: [
      Text(
        "$num",
        style: TextStyle(
          fontSize: WcaoTheme.fsXl,
          fontWeight: FontWeight.bold,
        ),
      ),
      Text(
        text,
        style: TextStyle(
          color: WcaoTheme.secondary,
        ),
      )
    ],
  );
}

Widget profile(UserInfoController _userInfoController) {
  return Center(
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Stack(
          children: [
            Container(
                alignment: Alignment.center,
                child: CircleAvatar(
                  radius: 48,
                  backgroundImage: NetworkImage(
                    _userInfoController.userInfo.value.avatarUrl,
                  ),
                )),
            _userInfoController.userSetting.value.isShowGender == 1
                ? Positioned(
                    bottom: 0,
                    right: 0,
                    left: 54,
                    child: Container(
                      width: 24,
                      height: 24,
                      child: Image.asset(
                        _userInfoController.userInfo.value.gender == 1
                            ? 'assets/images/icons/gender1.png'
                            : 'assets/images/icons/gender0.png',
                      ),
                    ))
                : Container()
          ],
        ),
        Container(
          margin: const EdgeInsets.only(top: 12),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                _userInfoController.userInfo.value.name,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: WcaoTheme.fsXl,
                  fontWeight: FontWeight.bold,
                ),
              ),
              SizedBox(
                width: 4,
              ),
              InkWell(
                child: Container(
                  height: 18,
                  alignment: Alignment.bottomLeft,
                  child: Image.asset(
                    'assets/images/icons/edit_userInfo.png',
                    width: 14,
                    height: 14,
                    color: Colors.grey[50],
                  ),
                ),
                onTap: () async => {Get.to(UserInfoIndexPage())},
              )
            ],
          ),
        ),
        Container(
          margin: const EdgeInsets.only(top: 12),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              InkWell(
                onTap: () {
                  Get.to(FriendListIndexPage(1));
                },
                child: Text(
                  '${_userInfoController.countInfo.value.followCount} 好友  | ',
                  style: TextStyle(
                    color: WcaoTheme.placeholder,
                  ),
                ),
              ),
              InkWell(
                  onTap: () {
                    Get.to(FriendListIndexPage(2));
                  },
                  child: Text(
                    ' ${_userInfoController.countInfo.value.fansCount} 粉丝',
                    style: TextStyle(
                      color: WcaoTheme.placeholder,
                    ),
                  ))
            ],
          ),
        ),
        Container(
            margin: const EdgeInsets.only(top: 6, right: 16, left: 16),
            child: Column(
              children: [
                _userInfoController.userInfo.value.description != ""
                    ? Container(
                        margin: const EdgeInsets.only(bottom: 10),
                        child: Tag(
                          _userInfoController.userInfo.value.description,
                          padding: const EdgeInsets.symmetric(
                              horizontal: 12, vertical: 4),
                          backgroundColor: Colors.black.withOpacity(.4),
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(24),
                          fontSize: 12,
                          // fontWeight: FontWeight.bold,
                        ))
                    : Container(),
                Wrap(
                  alignment: WrapAlignment.center,
                  spacing: 12,
                  runSpacing: 6,
                  children: [
                    _userInfoController.userSetting.value.isShowBirthday != 0 &&
                            _userInfoController.userInfo.value.birthday != ""
                        ? Tag(
                            _userInfoController
                                        .userSetting.value.isShowBirthday ==
                                    2
                                ? getAge(_userInfoController
                                        .userInfo.value.birthday) +
                                    "岁"
                                : getConstellation(_userInfoController
                                    .userInfo.value.birthday),
                            padding: const EdgeInsets.symmetric(
                                horizontal: 12, vertical: 4),
                            backgroundColor: Colors.black.withOpacity(.4),
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(24),
                            fontSize: 12,
                            // fontWeight: FontWeight.bold,
                          )
                        : Container(
                            width: 0,
                          ),
                    _userInfoController.userSetting.value.isShowCity == 1 &&
                            _userInfoController.userInfo.value.province != ""
                        ? Tag(
                            _userInfoController.userInfo.value.province +
                                _userInfoController.userInfo.value.city,

                            padding: const EdgeInsets.symmetric(
                                horizontal: 12, vertical: 4),
                            backgroundColor: Colors.black.withOpacity(.4),
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(24),
                            fontSize: 12,
                            // fontWeight: FontWeight.bold,
                          )
                        : Container(
                            width: 0,
                          ),
                    _userInfoController.userSetting.value.isShowSchool == 1 &&
                            _userInfoController.userInfo.value.university != ""
                        ? Tag(
                            _userInfoController.userInfo.value.university,
                            padding: const EdgeInsets.symmetric(
                                horizontal: 12, vertical: 4),
                            backgroundColor: Colors.black.withOpacity(.4),
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(24),
                            fontSize: 12,
                            // fontWeight: FontWeight.bold,
                          )
                        : Container()
                  ],
                ),
              ],
            )),
      ],
    ),
  );
}
